1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import static com.google.common.collect.CollectPreconditions.checkNonnegative;
20  
21  import com.google.common.annotations.GwtCompatible;
22  import com.google.common.annotations.VisibleForTesting;
23  
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.HashMap;
27  import java.util.List;
28  
29  /**
30   * Implementation of {@code Multimap} that uses an {@code ArrayList} to store
31   * the values for a given key. A {@link HashMap} associates each key with an
32   * {@link ArrayList} of values.
33   *
34   * <p>When iterating through the collections supplied by this class, the
35   * ordering of values for a given key agrees with the order in which the values
36   * were added.
37   *
38   * <p>This multimap allows duplicate key-value pairs. After adding a new
39   * key-value pair equal to an existing key-value pair, the {@code
40   * ArrayListMultimap} will contain entries for both the new value and the old
41   * value.
42   *
43   * <p>Keys and values may be null. All optional multimap methods are supported,
44   * and all returned views are modifiable.
45   *
46   * <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link
47   * #replaceValues} all implement {@link java.util.RandomAccess}.
48   *
49   * <p>This class is not threadsafe when any concurrent operations update the
50   * multimap. Concurrent read operations will work correctly. To allow concurrent
51   * update operations, wrap your multimap with a call to {@link
52   * Multimaps#synchronizedListMultimap}.
53   * 
54   * <p>See the Guava User Guide article on <a href=
55   * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
56   * {@code Multimap}</a>.
57   *
58   * @author Jared Levy
59   * @since 2.0 (imported from Google Collections Library)
60   */
61  @GwtCompatible(serializable = true, emulated = true)
62  public final class ArrayListMultimap<K, V> extends AbstractListMultimap<K, V> {
63    // Default from ArrayList
64    private static final int DEFAULT_VALUES_PER_KEY = 3;
65  
66    @VisibleForTesting transient int expectedValuesPerKey;
67  
68    /**
69     * Creates a new, empty {@code ArrayListMultimap} with the default initial
70     * capacities.
71     */
72    public static <K, V> ArrayListMultimap<K, V> create() {
73      return new ArrayListMultimap<K, V>();
74    }
75  
76    /**
77     * Constructs an empty {@code ArrayListMultimap} with enough capacity to hold
78     * the specified numbers of keys and values without resizing.
79     *
80     * @param expectedKeys the expected number of distinct keys
81     * @param expectedValuesPerKey the expected average number of values per key
82     * @throws IllegalArgumentException if {@code expectedKeys} or {@code
83     *      expectedValuesPerKey} is negative
84     */
85    public static <K, V> ArrayListMultimap<K, V> create(
86        int expectedKeys, int expectedValuesPerKey) {
87      return new ArrayListMultimap<K, V>(expectedKeys, expectedValuesPerKey);
88    }
89  
90    /**
91     * Constructs an {@code ArrayListMultimap} with the same mappings as the
92     * specified multimap.
93     *
94     * @param multimap the multimap whose contents are copied to this multimap
95     */
96    public static <K, V> ArrayListMultimap<K, V> create(
97        Multimap<? extends K, ? extends V> multimap) {
98      return new ArrayListMultimap<K, V>(multimap);
99    }
100 
101   private ArrayListMultimap() {
102     super(new HashMap<K, Collection<V>>());
103     expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
104   }
105 
106   private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) {
107     super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
108     checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey");
109     this.expectedValuesPerKey = expectedValuesPerKey;
110   }
111 
112   private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) {
113     this(multimap.keySet().size(),
114         (multimap instanceof ArrayListMultimap) ?
115             ((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey :
116             DEFAULT_VALUES_PER_KEY);
117     putAll(multimap);
118   }
119 
120   /**
121    * Creates a new, empty {@code ArrayList} to hold the collection of values for
122    * an arbitrary key.
123    */
124   @Override List<V> createCollection() {
125     return new ArrayList<V>(expectedValuesPerKey);
126   }
127 
128   /**
129    * Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
130    */
131   public void trimToSize() {
132     for (Collection<V> collection : backingMap().values()) {
133       ArrayList<V> arrayList = (ArrayList<V>) collection;
134       arrayList.trimToSize();
135     }
136   }
137 }
138